package com.solomiao.demo.multi.thread.demo2;

import com.solomiao.demo.multi.thread.demo1.ThreadExtendDemo1;
import com.solomiao.demo.multi.thread.demo1.ThreadImplementDemo1;

/**
 * @desc 线程的停止
 * */
public class MainDemo2 {

    public static void main(String[] args) throws InterruptedException {
        // 通过标志位停止线程
        // 通过实现Runnable接口创建线程
        ThreadImplementDemo2 threadImplementDemo = new ThreadImplementDemo2();
        Thread thread = new Thread(threadImplementDemo);
        // 启动线程
        thread.start();
        Thread.sleep(2000);
        System.out.println("主线程：准备停止子线程...");
        // 调用setRunning方法，将isRunning设置为false，线程会在循环中检测到并退出
        threadImplementDemo.setRunning(false);
        System.out.println("主线程：等待子线程退出...");
        // 等待子线程退出，join方法会阻塞当前线程，直到被调用的线程执行完毕
        thread.join();
        System.out.println("主线程：子线程已退出");

        // 通过interrupt方法停止线程
        System.out.println("主线程：准备重新启动子线程...");
        ThreadImplementDemo2 threadImplementDemo2 = new ThreadImplementDemo2();
        thread = new Thread(threadImplementDemo2);
        thread.start();
        Thread.sleep(5000); // 主线程等待5秒后停止线程
        thread.interrupt();
        System.out.println("主线程：子线程已被中断");
    }


}
